package com.bins.smartdoc.service;

import com.bins.smartdoc.dao.UserDao;
import com.bins.smartdoc.exception.ServiceException;
import com.bins.smartdoc.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 添加用户
     */
    public void addUser(User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userDao.save(user);
    }

    /**
     * 根据id进行修改用户
     *
     * @param user
     */
    public void updateUser(User user) {
        Optional<User> userOptional = userDao.findById(user.getId());
        if (!userOptional.isPresent()) {
            throw new ServiceException("用户不存在");
        }
        User userExist = userOptional.get();
        userExist.setPassword(user.getPassword());
        userExist.setEmail(user.getEmail());
        userExist.setPhone(user.getPhone());
        userExist.setUserCode(user.getUserCode());
        userExist.setUserName(user.getUserName());
        userExist.setStatus(user.getStatus());
        userDao.save(userExist);
    }

    /**
     * 根据id进行删除
     *
     * @param id
     */
    public void deleteUser(Long id) {
        userDao.deleteById(id);
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    public List<User> listUser() {
        return userDao.findAll();
    }

    /**
     * 根据id查询一条数据
     *
     * @param id
     * @return
     */
    public User findById(Long id) {
        return userDao.findById(id).get();
    }

}
